package com.sales.controller;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.sales.client.*;
import com.sales.service.QuotationDetService;
import com.sales.service.QuotationService;
import com.sales.util.UniqueOrderCode;
import org.comple.erp.pojo.base.enterprise.Staff;
import org.comple.erp.pojo.sales.Quotation;
import org.comple.erp.pojo.sales.QuotationDet;
import org.comple.erp.utils.AjaxResult;
import org.comple.erp.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
@RestController
public class QuotationController  {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private QuotationService quotationServiceImpl;

    @Autowired
    private QuotationDetService quotationDetServiceImpl;

    @Autowired
    private UniqueOrderCode uniqueOrderCode;

    @Autowired
    private GoodsClient goodsClient;

    @Autowired
    private CustomerClient customerClient;

    @Autowired
    private CustomerLevelClient customerLevelClient;

    @Autowired
    private CustomerTypeClient customerTypeClient;

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private StaffSalesClient staffSalesClient;

    @RequestMapping("/quotationList")
    public AjaxResult quotationList(@RequestParam Map<String, Object> params, HttpServletRequest request) {

        String token = request.getHeader("Authorization");
        String userId = JwtUtil.getUserId(token);
        String companyCode = JwtUtil.getCompanyCode(token);
        params.put("company_code", companyCode);
        Map<String, Object> staff = (Map<String, Object>) staffSalesClient.selectById(userId).get("staff");
        List<String> list  = (List<String>) staff.get("roleIds");
        for(String roleId : list){
            if(roleId.equals("2")){
                params.put("workNumber", staff.get("id"));
            }
        }

        PageInfo<Quotation> quotationList = quotationServiceImpl.quotationList(params);
        return AjaxResult.back("200","查询成功").add("quotationList",quotationList);
    }
    //    @RequestMapping("/goodsList")
//    public AjaxResult goodsList(@RequestParam Map<String, Object> params) {
//        PageInfo<Goods> goodsList = goodsClient.getGoodsByParam(params);
//        return AjaxResult.back("200", "查询成功").add("goodsList", goodsList);
//    }

    // 计算时间差
    private long getTimeDifferenceInSeconds(Date startDate, Date endDate) {
        if (startDate == null || endDate == null) {
            return 0;
        }
        long milliseconds = endDate.getTime() - startDate.getTime();
        return milliseconds / 1000;
    }



    @PostMapping("/quotationAdd") // 建议明确使用 @PostMapping
    public synchronized AjaxResult quotationAdd( @RequestBody Map<String, Object> params, HttpServletRequest request) throws InterruptedException {

        String token = request.getHeader("Authorization");
        String  userId = JwtUtil.getUserId(token);
        String companyCode = JwtUtil.getCompanyCode(token);

        // 提取并转换主表数据
        Map<String, Object> quotationMap = (Map<String, Object>) params.get("quotation");
        List<Map<String, Object>> quotationDetMapList = (List<Map<String, Object>>) params.get("quotationDetList");

        if (quotationMap == null || quotationDetMapList == null) {
            return AjaxResult.back("500", "参数错误");
        }

        // 转换为主表对象
        Quotation quotation = objectMapper.convertValue(quotationMap, Quotation.class);

        quotation.setId(UUID.randomUUID().toString());
        String quotationCode = "BJ"+uniqueOrderCode.getCode("cd001", "QUOTATION");
        quotation.setCode(quotationCode);
        quotation.setWorkNumber(userId);
        quotation.setCompany_code(companyCode);
//        uniqueOrderCode.getCode(quotation.getCompany_code(), "QUOTATION");

        long durationInSeconds = getTimeDifferenceInSeconds(
             quotation.getStart_date(),
             quotation.getEnd_date()
        );
        redisTemplate.opsForValue().set(quotation.getId(),quotation.getId(),durationInSeconds, TimeUnit.SECONDS);

        // 转换为明细列表
        List<QuotationDet> quotationDetList = quotationDetMapList.stream()
                .map(map -> objectMapper.convertValue(map, QuotationDet.class))
                .collect(Collectors.toList());

        // 保存数据
        Boolean flag = quotationServiceImpl.insertSelective(quotation);
        if (!flag) {
            return AjaxResult.back("500", "报价单添加失败");
        }

        // 保存明细数据
        for (QuotationDet quotationDet : quotationDetList) {
            quotationDet.setId(UUID.randomUUID().toString());
            quotationDet.setQuotation_code(quotation.getCode());
            if (!quotationDetServiceImpl.insertSelective(quotationDet)) {
                return AjaxResult.back("500", "报价单详情添加失败");
            }
        }

        return AjaxResult.back("200", "添加成功").add("quotationCode", quotationCode).add("id", quotation.getId());

    }

    @RequestMapping("/selectQuotation")
    public AjaxResult selectQuotation(@RequestParam String id) {
        Quotation quotation = quotationServiceImpl.selectByPrimaryKey(id);
        List<QuotationDet> quotationDetList = quotationDetServiceImpl.selectByQuotationCode(quotation.getCode());
        if(quotation != null && quotationDetList != null){
            return AjaxResult.back("200","查询成功").add("quotation", quotation).add("quotationDetList", quotationDetList);
        }
        return AjaxResult.back("500","查询失败");
    }


    @RequestMapping("/updateQuotation")
    public synchronized AjaxResult updateQuotation(@RequestBody Map<String, Object> request) {
        // 提取并转换主表数据
        Map<String, Object> quotationMap = (Map<String, Object>) request.get("quotation");
        List<Map<String, Object>> quotationDetMapList = (List<Map<String, Object>>) request.get("quotationDetList");

        if (quotationMap == null || quotationDetMapList == null) {
            return AjaxResult.back("500", "参数错误");
        }

        // 转换为主表对象
        Quotation quotation = objectMapper.convertValue(quotationMap, Quotation.class);

        // 转换为明细列表
        List<QuotationDet> quotationDetList = quotationDetMapList.stream()
                .map(map -> objectMapper.convertValue(map, QuotationDet.class))
                .collect(Collectors.toList());


        long durationInSeconds = getTimeDifferenceInSeconds(
                quotation.getStart_date(),
                quotation.getEnd_date()
        );
        redisTemplate.opsForValue().set(quotation.getId(),quotation.getId(),durationInSeconds, TimeUnit.SECONDS);

        // 保存数据
        Boolean flag = quotationServiceImpl.updateByPrimaryKeySelective(quotation);
        if (!flag) {
            return AjaxResult.back("500", "报价单修改失败");
        }

        if(quotationDetList != null && quotationDetList.size() > 0){
            quotationDetServiceImpl.deleteByCode(quotation.getCode());
        }


        // 保存明细数据
        for (QuotationDet quotationDet : quotationDetList) {
            quotationDet.setQuotation_code(quotation.getCode());
            quotationDet.setId(UUID.randomUUID().toString());
            Boolean flag1 = quotationDetServiceImpl.insertSelective(quotationDet);
            if (!flag1) {
                return AjaxResult.back("500", "报价单详情修改失败");
            }
        }

        return AjaxResult.back("200", "修改成功");
    }


    @RequestMapping("deleteQuotation")
    public AjaxResult deleteQuotation(@RequestBody  List< String>  id) {
        for(String c : id){
            Boolean flag = quotationServiceImpl.deleteByPrimaryKey(c);
            if (!flag) {
                return AjaxResult.back("500", "删除失败");
            }
        }
        return AjaxResult.back("200", "删除成功");
    }

    @RequestMapping ("/selectOtherList")
    public AjaxResult selectOtherList(){
        Map<String, Object> params = new HashMap<>();
        List<LinkedHashMap<String, Object>> customerLevelList = (List<LinkedHashMap<String, Object>>)customerLevelClient.selectAll().get("customerLevels");
        List<LinkedHashMap<String, Object>> customerTypeList = (List<LinkedHashMap<String, Object>>)customerTypeClient.selectCustomerTypeList(params).get("customerTypeList");
        List<LinkedHashMap<String, Object>> customerList = (List<LinkedHashMap<String, Object>>)customerClient.getAllCustomerList().get("customerList");
        return AjaxResult.back("200", "查询成功").add("customerLevelList", customerLevelList).add("customerTypeList", customerTypeList).add("customerList", customerList);
    }

}
